//
//  LQEmotIconKey.swift
//  emotIcon
//
//  Created by 半缘君 on 15/12/15.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
let LQCollectionViewCell = "CollectionViewCell"
class LQEmotIconKeyboard: UIView {
    
    //完成回调
    var didclickEmotIconCallBack:(em:Emoticon) -> ()
    
    @objc private func clickItmeButton (barItem:UIBarButtonItem) {
//        print(barItem)
        let index = NSIndexPath(forItem: 0, inSection: barItem.tag)
        collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: LQFlowLayout())
    private lazy var toolBar = UIToolbar()
    
    private lazy var packages:[EmotIconGroup] = EmotIconGroupManager.shareEmotManager.packages
    
    //MARK: - 构造函数
    
    init(clickEmotIconCallBack:(em:Emoticon) -> ()){
        didclickEmotIconCallBack = clickEmotIconCallBack
        var frame = UIScreen.mainScreen().bounds
        frame.size.height = 226
        super.init(frame: frame)
        
        setupUI()
        //注册cell
        collectionView.registerClass(LQEmotIconCell.self, forCellWithReuseIdentifier: LQCollectionViewCell)
        
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class LQFlowLayout: UICollectionViewFlowLayout {
      override func invalidateLayout () {
            super.invalidateLayout()
        let rowCount:CGFloat = 3
        let colCount:CGFloat = 7
        
        let widthForScreen = UIScreen.mainScreen().bounds.width
        let w = widthForScreen / colCount
        let h = w
        let margin = ((collectionView?.bounds.size.height)! - rowCount * w) /  2
        itemSize = CGSize(width: w, height: h)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin
        , right: 0)
        scrollDirection = .Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
        }
    }
    
}
//MARK: - 添加视图
private extension LQEmotIconKeyboard {
   func setupUI(){
//            backgroundColor = UIColor.redColor()
    addSubview(collectionView)
    addSubview(toolBar)
    toolBar.snp_makeConstraints { (make) -> Void in
        make.left.equalTo(self)
        make.right.equalTo(self)
        make.bottom.equalTo(self)
        make.height.equalTo(36)
    }
    collectionView.snp_makeConstraints { (make) -> Void in
        make.top.equalTo(self)
        make.left.equalTo(self)
        make.right.equalTo(self)
        make.bottom.equalTo(toolBar.snp_top)
    }
        prepareToolBar()
        prepareCollection()
    }
    /// 准备底部工具条
    func prepareToolBar () {
//        let options = packages
//        ["常用","默认","emoji","浪小花"]
        var items = [UIBarButtonItem]()
        var index = 0
        for s in packages {
            let barItem = UIBarButtonItem(title: s.group_name_cn,
                                          style: UIBarButtonItemStyle.Plain,
                                         target: self,
                                         action: "clickItmeButton:")
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            items.append(barItem)
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
//        items.removeLast()
        toolBar.items = items
        
    }
    func prepareCollection () {
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }
}
extension LQEmotIconKeyboard : UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let em = packages[indexPath.section].emoticons[indexPath.item]
        didclickEmotIconCallBack(em: em)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return  packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LQCollectionViewCell, forIndexPath: indexPath) as! LQEmotIconCell
        cell.emotIcon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}

private class LQEmotIconCell:UICollectionViewCell {
    
    private lazy var emotIconBtn:UIButton = UIButton()
    

    var emotIcon:Emoticon? {
        didSet {
//            print((emotIcon?.imagePath)!)
            if let name = emotIcon?.imagePath {
        emotIconBtn.setImage(UIImage(named: name), forState: UIControlState.Normal)
            } else{
                emotIconBtn.setImage(nil, forState: UIControlState.Normal)
            }
            emotIconBtn.setTitle(emotIcon?.emoji, forState: UIControlState.Normal)
            if emotIcon?.isRemoved == true {
                emotIconBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emotIconBtn)

//        emotIconBtn.backgroundColor = UIColor.whiteColor()
        emotIconBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        emotIconBtn.frame = CGRectInset(bounds, 4, 4)
        emotIconBtn.userInteractionEnabled = false
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

